/*
 * @Author: 9ilk 3535851673@qq.com
 * @Date: 2024-11-05 16:57:40
 * @LastEditors: 9ilk 3535851673@qq.com
 * @LastEditTime: 2024-11-05 22:42:17
 * @FilePath: /zhuang/namePipe/Server.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once
#include <iostream>
#include "Comm.hpp"
using namespace std;

class Init
{
public:
    Init()
    {
        umask(0);
        int n = ::mkfifo(gpipefile.c_str(), gmode);
        if (n < 0) // 创建失败
        {
            cerr << "mkfifo error" << endl;
            return;
        }
        cout << "mkfifo success" << endl;
        sleep(10);
    }
    ~Init()
    {
        int n = unlink(gpipefile.c_str());
        if (n < 0)
        {
            cerr << "unlink error" << endl;
            return;
        }
        cout << "unlink success" << endl;
    }
};

Init init;

class Server
{
public:
    Server()
        : _fd(gdeafultfd)
    {}
    // 打开管道
    bool OpenPipe()
    {
        _fd = ::open(gpipefile.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            cerr << "open fail" << endl;
            return false;
        }
        return true;
    }

    // 读管道就是读文件
    int RecvPipe(string *out)
    {
        char buffer[gsize];
        ssize_t n = ::read(_fd, buffer, sizeof(buffer));
        // 我们将数据当成字符串
        if (n > 0)
        {
            buffer[n] = 0;
            *out = buffer;
        }
        return n;
    }

    // 关闭管道
    void ClosePipe()
    {
        if (_fd >= 0)
            ::close(_fd);
    }

    ~Server()
    {}

private:
    int _fd;
};